package asa;

import java.util.List;

import crawler.Crawler;

import output.Output;
import translate.Translate;

import forum.ForumFactory;
import forum.ForumPost;

/**
 * Closes down the pipeline cleanly on unexpected shutdowns.
 */
public class Shutdown extends Thread {
	private Pipeline[] pipelines;
	private List<Crawler> crawlers;
	private Translate[] translators;
	private PostBucket outBucket;
	private PostBucket translateBucket;
	private Output output;
	private ForumFactory fac;
	private MainThreadPass pass;

	public Shutdown(Pipeline[] pipelines, List<Crawler> crawlers,
			Translate[] translators, PostBucket translateBucket,
			PostBucket outBucket, Output output, ForumFactory fac, MainThreadPass pass) {
		this.pass = pass;
		this.pipelines = pipelines;
		this.crawlers = crawlers;
		this.translators = translators;
		this.translateBucket = translateBucket;
		this.outBucket = outBucket;
		this.output = output;
		this.fac = fac;
	}

	public void run() {

		for (Pipeline pipeline : pipelines)
			pipeline.interrupt();

		if (translators != null)
			for (Translate translator : translators)
				translator.interrupt();

		for (Crawler crawler : crawlers)
			crawler.interrupt();

		try {
			while (translateBucket.size() > 0) {
				List<ForumPost> posts = translateBucket.getPost();
				if (posts == null) {
					break;
				}
				outBucket.addPost(posts);
			}

			while (outBucket.size() > 0) {
				List<ForumPost> ft = outBucket.getPost();
				if (ft == null)
					break;
				try {
					output.outputThread(ft);
				} catch (Exception oe) {
				}
			}
			try {
				pass.waitForIt();
				output.close();
			} catch (Exception oe) {
			}
			fac.store();
			System.err.println("Finished!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
